package com.neusoft.elmboot.service.impl;

import com.neusoft.elmboot.mapper.UserMapper;
import com.neusoft.elmboot.po.User;
import com.neusoft.elmboot.service.SuperMemberService;
import com.neusoft.elmboot.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@Service
public class SuperMemberServiceImpl implements SuperMemberService {
	
	@Autowired
	private UserMapper userMapper;
	
	@Autowired
	private UserService userService;
	
	@Override
	public User getSuperMemberStatus(String userId) {
		User user = userService.getUserInfoById(userId);
		if (user != null) {
			// 检查会员是否过期
			boolean isValid = isValidSuperMember(userId);
			if (!isValid && user.getIsSuperMember() != null && user.getIsSuperMember() == 1) {
				// 如果已过期，更新状态
				userMapper.updateSuperMemberStatus(userId, 0, null);
				user.setIsSuperMember(0);
				user.setSuperMemberExpireTime(null);
			}
		}
		return user;
	}
	
	@Override
	@Transactional
	public boolean purchaseSuperMember(String userId, int duration) {
		User user = userService.getUserInfoById(userId);
		if (user == null) {
			return false;
		}
		
		LocalDateTime now = LocalDateTime.now();
		LocalDateTime expireTime;
		
		// 如果已经是会员且未过期，在原有基础上延长
		if (isValidSuperMember(userId)) {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime currentExpireTime = LocalDateTime.parse(user.getSuperMemberExpireTime(), formatter);
			expireTime = currentExpireTime.plusMonths(duration);
		} else {
			// 新购买或已过期，从当前时间开始计算
			expireTime = now.plusMonths(duration);
		}
		
		DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
		String expireTimeStr = expireTime.format(formatter);
		
		userMapper.updateSuperMemberStatus(userId, 1, expireTimeStr);
		return true;
	}
	
	@Override
	public boolean isValidSuperMember(String userId) {
		User user = userService.getUserInfoById(userId);
		if (user == null) {
			return false;
		}
		
		if (user.getIsSuperMember() == null || user.getIsSuperMember() == 0) {
			return false;
		}
		
		if (user.getSuperMemberExpireTime() == null || user.getSuperMemberExpireTime().isEmpty()) {
			return false;
		}
		
		try {
			DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
			LocalDateTime expireTime = LocalDateTime.parse(user.getSuperMemberExpireTime(), formatter);
			return LocalDateTime.now().isBefore(expireTime);
		} catch (Exception e) {
			return false;
		}
	}
}

